const { Send } = require("../utils/response");
const Banner = require("../models/banner");

class BannerController {
    static async add(req, res, next) {
        try {
            const banner = await Banner.create({
                title: req.body.title,
                imageUrl: req.body.imageUrl,
                targetUrl: req.body.targetUrl
            });
            return Send(res, {
                data: banner,
                message: "创建成功"
            });
        } catch (error) {
            next(error);
        }
    }
    static async list(req, res, next) {
        try {
            const { keywords } = req.query;
            const regex = new RegExp(keywords, "i");
            const banners = await Banner.find({ title: { $regex: regex } })
                .select("+isActive +createdAt +order")
                .sort({
                    order: -1,
                    createdAt: -1
                });
            return Send(res, {
                data: banners
            });
        } catch (error) {
            next(error);
        }
    }
    static async delete(req, res, next) {
        try {
            const { deletedCount } = await Banner.deleteOne({
                _id: req.params.id
            });
            if (deletedCount === 0) {
                return Send(res, {
                    message: "该轮播图不存在"
                });
            }
            return Send(res, {
                message: "删除成功",
                data: req.params.id
            });
        } catch (error) {
            next(error);
        }
    }
    static async update(req, res, next) {
        try {
            if (!req.body) {
                return Send(res, {
                    code: -1,
                    message: "请填写要修改的参数"
                });
            }
            const banner = await Banner.findByIdAndUpdate(
                req.params.id,
                req.body
            );
            if (!banner) {
                return Send(res, {
                    code: -1,
                    message: "该轮播图不存在"
                });
            }
            Send(res, {
                message: "更新成功",
                data: banner._id
            });
        } catch (error) {
            next(error);
        }
    }
}

module.exports = BannerController;
